<?php
function P($data) {
    dump($data,1,'<pre>',0);die;
}
function formatUrl($str)
{
    if ($str != "") {
        $Urls = explode("http://", $str);
        if (count($Urls) != 0) {
            if (count($Urls) == 1) {
                $url = "http://" . $str;
            } else {
                $url = $str;
            }
        } else {
            $url = "javascript:void(0)";
        }
    } else {
        $url = "javascript:void(0)";
    }

    return $url;
}

/**
 * 获取数据的分类名称
 * @param $pid 位置ID
 */
function getTitle($id, $tbName = CONTROLLER_NAME, $field = 'name')
{
    if (!$str = M("$tbName")->where("id =$id ")->getField($field)) {
      $special = array("News_category","Banner_position","Goods_category","Service_category");
      if(in_array($tbName,$special))
        $str = '==顶级==';
    }

    return $str;
}


//格式化数字，位数不足补0
function format_num($str, $num, $prefix)
{
    return $prefix.sprintf("%0".($num-count($prefix))."d", $str);
}

//防脚本注入XSS
function RemoveXSS($val) {
   // remove all non-printable characters. CR(0a) and LF(0b) and TAB(9) are allowed
   // this prevents some character re-spacing such as <java\0script>
   // note that you have to handle splits with \n, \r, and \t later since they *are* allowed in some inputs
   $val = preg_replace('/([\x00-\x08,\x0b-\x0c,\x0e-\x19])/', '', $val);
   // straight replacements, the user should never need these since they're normal characters
   // this prevents like <IMG SRC=@avascript:alert('XSS')>
   $search = 'abcdefghijklmnopqrstuvwxyz';
   $search .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
   $search .= '1234567890!@#$%^&*()';
   $search .= '~`";:?+/={}[]-_|\'\\';
   for ($i = 0; $i < strlen($search); $i++) {
      // ;? matches the ;, which is optional
      // 0{0,7} matches any padded zeros, which are optional and go up to 8 chars
      // @ @ search for the hex values
      $val = preg_replace('/(&#[xX]0{0,8}'.dechex(ord($search[$i])).';?)/i', $search[$i], $val); // with a ;
      // @ @ 0{0,7} matches '0' zero to seven times
      $val = preg_replace('/(?{0,8}'.ord($search[$i]).';?)/', $search[$i], $val); // with a ;
   }
   // now the only remaining whitespace attacks are \t, \n, and \r
   $ra1 = array('javascript', 'vbscript', 'expression', 'applet', 'meta', 'xml', 'blink', 'link', 'style', 'script', 'embed', 'object', 'iframe', 'frame', 'frameset', 'ilayer', 'layer', 'bgsound', 'title', 'base');
   $ra2 = array('onabort', 'onactivate', 'onafterprint', 'onafterupdate', 'onbeforeactivate', 'onbeforecopy', 'onbeforecut', 'onbeforedeactivate', 'onbeforeeditfocus', 'onbeforepaste', 'onbeforeprint', 'onbeforeunload', 'onbeforeupdate', 'onblur', 'onbounce', 'oncellchange', 'onchange', 'onclick', 'oncontextmenu', 'oncontrolselect', 'oncopy', 'oncut', 'ondataavailable', 'ondatasetchanged', 'ondatasetcomplete', 'ondblclick', 'ondeactivate', 'ondrag', 'ondragend', 'ondragenter', 'ondragleave', 'ondragover', 'ondragstart', 'ondrop', 'onerror', 'onerrorupdate', 'onfilterchange', 'onfinish', 'onfocus', 'onfocusin', 'onfocusout', 'onhelp', 'onkeydown', 'onkeypress', 'onkeyup', 'onlayoutcomplete', 'onload', 'onlosecapture', 'onmousedown', 'onmouseenter', 'onmouseleave', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'onmousewheel', 'onmove', 'onmoveend', 'onmovestart', 'onpaste', 'onpropertychange', 'onreadystatechange', 'onreset', 'onresize', 'onresizeend', 'onresizestart', 'onrowenter', 'onrowexit', 'onrowsdelete', 'onrowsinserted', 'onscroll', 'onselect', 'onselectionchange', 'onselectstart', 'onstart', 'onstop', 'onsubmit', 'onunload');
   $ra = array_merge($ra1, $ra2);
   $found = true; // keep replacing as long as the previous round replaced something
   while ($found == true) {
      $val_before = $val;
      for ($i = 0; $i < sizeof($ra); $i++) {
         $pattern = '/';
         for ($j = 0; $j < strlen($ra[$i]); $j++) {
            if ($j > 0) {
               $pattern .= '(';
               $pattern .= '(&#[xX]0{0,8}([9ab]);)';
               $pattern .= '|';
               $pattern .= '|(?{0,8}([9|10|13]);)';
               $pattern .= ')*';
            }
            $pattern .= $ra[$i][$j];
         }
         $pattern .= '/i';
         $replacement = substr($ra[$i], 0, 2).'<x>'.substr($ra[$i], 2); // add in <> to nerf the tag
         $val = preg_replace($pattern, $replacement, $val); // filter out the hex tags
         if ($val_before == $val) {
            // no replacements were made, so exit the loop
            $found = false;
         }
      }
   }
   return $val;
}
//防sql注入
function abacaAddslashes($var) {
    if (! get_magic_quotes_gpc ()) {
        if (is_array ( $var )) {
            foreach ( $var as $key => $val ) {
                $var [$key] = abacaAddslashes ( $val );
            }
        } else {
            $var = addslashes ( $var );
        }
    }
    return $var;
}

//二级数组添加元素
function addkey(&$val ,$key, $param){ 
	$val[$param['key']] = $param['val'];
}

//数字转化为大写一，二，三...
function numCapital($number){
    $number=substr($number,0,2);
    $arr=array("零","一","二","三","四","五","六","七","八","九");
    if(strlen($number)==1){
        $result=$arr[$number];
    }else{
        if($number==10){
            $result="十";
        }else{
            if($number<20){
                $result="十";
            }else{
                $result=$arr[substr($number,0,1)]."十";
            }
            if(substr($number,1,1)!="0"){
                $result.=$arr[substr($number,1,1)];
            }
        }
    }
    return $result;
}

//当前月第一天及最后一天
function monthFirstLast(){
    $firstdate=date('Y-m-01 00:00:00');
    $firsttime=strtotime($firstdate);
    $lastdate = date('Y-m-d 23:59:59', strtotime("$firstdate +1 month -1 day"));
    $lasttime=strtotime($lastdate);
    $other=array(
        0=>$firsttime,
        1=>$lasttime
    );
    return $other;
}

/**
 * 获取微信授权token 
 * @return boolean
 */
function getAccessToken(){
    if(!S('access_token')){
        $wxTokenUrl = "https://api.weixin.qq.com/cgi-bin/token";
        $data = [
          'grant_type' => 'client_credential',
          'appid' => C('CONFIG.appid'),
          'secret' => C('CONFIG.appsecret')
        ];
        $access_token = curl($wxTokenUrl,$data);
        $access_token = json_decode($access_token,true);
        if(isset($access_token['errcode'])){
            debug($access_token);
            return false;
        }
        S('access_token',$access_token['access_token'],7200);
        return $access_token['access_token'];
    }
    return S('access_token');
}
    /**
     * 根据所要生成的文件夹，依次生成根目录文件夹
     * @access public
     * @param string $path 目标文件夹路径
     * @return boolean
     */
    function makeDir($path){
        $dir = explode(DS,$path);
        $root = $dir[0] = $dir[0].DS;
        for($i=0;$i<count($dir);$i++){
            if($i!=0){
                $tmpdir = $dir[$i-1];
                $tmpdir .= $dir[$i].DS;
                $dir[$i] = $tmpdir;
            }
        }
        if(!is_dir($root)){
            return false;
        }else{
            for($i=1;$i<count($dir);$i++){
                if(!is_dir($dir[$i])){
                    mkdir($dir[$i],0777);
                }
            }
        }
    }

/**
 * 邮件发送
 * @param type $subject 邮件标题
 * @param type $message 邮件内容
 * @param type $recipients 接收人 单个直接邮箱地址，多个可以使用数组
 * @param type $bcc 抄送
 * @param type $replyTo
 * @param type $html 是否为html邮件
 * @param type $attachment 用逗号分隔
 * @param type $mail_from 发件人
 * @param type $mail_fromname 发件人姓名
 */
function sendMail($subject, $message, $recipients, $cc = '', $bcc = '', $replyTo = '', $mail_from = '', $mail_fromname = '', $html = false, $attachment = '') {
    import("@.Util.Mail.PHPMailerAutoload");
    try {
        $mail = new PHPMailer();

        //check smtp
        $Config = C('Config');
        if ($Config['mail_mode'] == 1) {
            $mail->isSMTP(); // Set mailer to use SMTP
            $mail->Host = $Config['smtp_host']; // Specify main and backup server
            $mail->SMTPAuth = true; // Enable SMTP authentication
            $mail->Username = $Config['smtp_username']; // SMTP username
            $mail->Password = $Config['smtp_password']; // SMTP password
            $mail->SMTPSecure = $Config['smtp_secure'] ? $Config['smtp_secure'] : ''; // Enable encryption, 'tls' 'ssl' also accepted
        }

        $mail->CharSet = 'utf-8';
        $mail->From = $Config['smtp_username']; //默认为系统发件人邮箱
        $mail->FromName = $mail_fromname ? $mail_fromname : $Config['mail_fromname']; //默认为系统发件人姓名

        if (is_array($recipients)) {
            foreach ($recipients as $email => $name) {
                $mail->addAddress($email, $name); // Add a recipient
            }
        } else {
            $mail->addAddress($recipients);
        }
        if ($replyTo) {
            $mail->addReplyTo($replyTo);
        }
        if ($cc) {
            if (is_array($cc)) {
                foreach ($cc as $email => $name) {
                    $mail->addCC($email, $name); // Add CC
                }
            } else {
                $mail->addCC($cc);
            }
        }
        if ($bcc) {
            if (is_array($bcc)) {
                foreach ($bcc as $email => $name) {
                    $mail->addBCC($email, $name); // Add BCC
                }
            } else {
                $mail->addBCC($bcc);
            }
        }

        //$mail->WordWrap = 50;                                 // Set word wrap to 50 characters
        //添加附件
        if ($attachment) {
            $attachmentArray = explode(",", $attachment);
            foreach ($attachmentArray as $file) {
                if (is_file($file)) {
                    $mail->addAttachment($file); // Add attachments
                }
            }
        }

        // Set email format to HTML
        if ($html) {
            $mail->isHTML(true);
        }

        $mail->Subject = $subject;
        $mail->Body = $message;

        //$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';

        return $mail->send();
    } catch (phpmailerException $e) {
        return $e->errorMessage();
    }
}

/**
 * 取邮件模板，from email表
 */
function getEmailConfig($key) {
    return M('Email')->where(array('key' => $key))->find();
}


/**
 * 根据上传文件命名规则取得保存文件名(符合tp规则)
 * @access private
 * @param string $name 数据
 * @return string
 */
function uniqidName($name)
{
	$extension = array_pop(explode('.', $name));
	return uniqid() . "." . $extension;
}


//判断是否是苹果系统
function is_ios()
{
	$agent = strtolower($_SERVER['HTTP_USER_AGENT']);
	$is_pc = (strpos($agent, 'windows nt')) ? true : false;
	$is_mac = (strpos($agent, 'mac os')) ? true : false;
	$is_iphone = (strpos($agent, 'iphone')) ? true : false;
	$is_ipad = (strpos($agent, 'ipad')) ? true : false;

	if($is_pc){
		  return  false;
	}
	
	if($is_mac){
		  return  true;
	}
	
	if($is_iphone){
		  return  true;
	}
	if($is_ipad){
		  return  true;
	}
}

//判断是否是手机
function is_mobile()
{
	$agent = strtolower($_SERVER['HTTP_USER_AGENT']);
	
	$is_iphone = (strpos($agent, 'iphone')) ? true : false;
	$is_android = (strpos($agent, 'android')) ? true : false;
		
	if($is_iphone){
		  return  true;
	}
	
	if($is_android){
		  return  true;
	}

}


	/*
	 * 删除文件
	 * @param $path  
	 * @return $info
	 */
	function delFile($path) {
		$flag="";
		if(!is_dir($path)){
			$pathInfo = pathinfo($path);
			$flag = unlink($pathInfo['dirname'].'/'.$pathInfo['basename']);
		}else {//否则就是目录，调用方法进行删除该目录下的所有文件
			$flag = $this->deldir($path);
		}
		return $flag;
	}

	function deldir($dir) {
		//先删除目录下的文件：
		$dh = opendir($dir);
		while ($file = readdir($dh)) {
			if ($file != "." && $file != "..") {
				$fullpath = $dir . "/" . $file;
				if (!is_dir($fullpath)) {
					unlink($fullpath);
				} else {
					deldir($fullpath);
				}
			}
		}

		closedir($dh);
		//删除当前文件夹：
		if (rmdir($dir)) {
			return true;
		} else {
			return false;
		}
	}

    //测试DEBUG
    function debug($str,$filename = 'log.txt') {
        $dir = C('LOG').DS.date('Ym',time()).DS.date('d',time());
        if(!is_dir($dir)){
            makeDir($dir);
        }
        $Path = $dir.DS.$filename;
        $fp = fopen($Path, "a+");
        if (is_array($str)) {
            $tempstr = urldecode(http_build_query($str)) . PHP_EOL;
            fwrite($fp, $tempstr);
        }elseif(is_object($str)){
            $tempstr = urldecode(http_build_query($str)) . PHP_EOL;
            fwrite($fp, $tempstr);
        } else {
            fwrite($fp, $str . PHP_EOL);
        }
        fwrite($fp, 'time => '.date('Y-m-d H:i:s') . PHP_EOL.PHP_EOL);
        fclose($fp);
    }

    //数组转xml
    function arrToxml($arr)
    {
        if(!is_array($arr) 
            || count($arr) <= 0)
        {
            echo "数组数据异常！";die;
        }
        
        $xml = "<xml>";
        foreach ($arr as $key=>$val)
        {
            // if (is_numeric($val)){
            //     $xml.="<".$key.">".$val."</".$key.">";
            // }else{
            //     $xml.="<".$key."><![CDATA[".$val."]]></".$key.">";
            // }
            $xml.="<".$key.">".$val."</".$key.">";
        }
        $xml.="</xml>";
        return $xml; 
    }

    /**
     * xml转array
     */
    function xmlToarr($xml)
    {   
        if(!$xml){
            echo "xml数据异常！";
        }
        //将XML转为array
        //禁止引用外部xml实体
        libxml_disable_entity_loader(true);
        $order_return = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);        
        return $order_return;
    }

    /**
     * 以post方式提交xml到对应的接口url
     * 
     * @param string $xml  需要post的xml数据
     * @param string $url  url
     * @param int $second   url执行超时时间，默认30s
     */
    function postXmlCurl($xml, $url, $second = 30)
    {       
        $ch = curl_init();
        //设置超时
        curl_setopt($ch, CURLOPT_TIMEOUT, $second);
        
        //如果有配置代理这里就设置代理
        curl_setopt($ch,CURLOPT_URL, $url);
        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,FALSE);
        curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,FALSE);//严格校验
        //设置header
        curl_setopt($ch, CURLOPT_HEADER, FALSE);
        //要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    
        //post提交方式
        curl_setopt($ch, CURLOPT_POST, TRUE);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
        //运行curl
        $data = curl_exec($ch);
        //返回结果
        if($data){
            curl_close($ch);
            return $data;
        } else { 
            $error = curl_errno($ch);
            curl_close($ch);
            echo "curl出错，错误码:$error";
        }
    }

	//对象转数组
	function object_to_array($d)
	{
		if (is_object($d)) $d = get_object_vars($d);
		if (is_array($d)){
			return array_map('object_to_array', $d);
		}else{
			return $d;
		}
	}
    /**
     * 生成二维码
     * @param   $data     二维码包含的信息(完整的链接+程序处理时所需要的参数值,例如'http://'.$_SERVER['HTTP_HOST'].U('user/index',array('invite_code' => $invite_code));)
     * @param   $filename 文件名(例如:123.png)
     * @param   $picPath  上传文件路径
     * @param   $logo     logo(图片完整地址,注:微信头像需进行处理,若为https网址,windows系统下打开php.ini找到 ;extension=php_openssl.dll ，去掉双引号”;”)
     * @param   $is_wxlogo 是否为微信头像,如果为微信头像则需要对头像进行处理
     * @param   $size     图片尺寸
     * @param   $level    识别错误级别 ( L-默认：可以识别已损失的7%的数据 M-可以识别已损失15%的数据 Q-可以识别已损失25%的数据 H-可以识别已损失30%的数据)
     * @param   $padding  内边距
     *
     */
    function qrcode($data,$filename,$picPath=false,$logo=false,$is_wxlogo=false,$size='4',$level='L',$padding=2,$saveandprint=false){
        vendor("phpqrcode.phpqrcode");//(解压phpqrcode.zip,放入指定文件夹)引入工具包，此处以tp3.2框架为例，此文件放在“项目/Core/Library/Vendor”文件夹下
        // 下面注释了把二维码图片保存到本地的代码,如果要保存图片,用$fileName替换第二个参数false
        $path = $picPath?$picPath:"./Uploads/Picture/QRcode/"; //图片输出路径
        makeDir($path);
        //在二维码上面添加LOGO
        if(empty($logo) || $logo=== false) { //不包含LOGO
            if ($filename==false) {
                \QRcode::png($data, false, $level, $size, $padding, $saveandprint); //直接输出到浏览器，不含LOGO
            }else{
                $filename=$path.'/'.$filename; //合成路径
                // P($filename);
                \QRcode::png($data, $filename, $level, $size, $padding, $saveandprint); //直接输出到浏览器，不含LOGO
            }
        }else { //包含LOGO
            if ($filename==false){
                //$filename=tempnam('','').'.png';//生成临时文件
                die('参数错误');
            }else {
                //生成二维码,保存到文件
                $filename = $path . '\\' . $filename; //合成路径
            }
            \QRcode::png($data, $filename, $level, $size, $padding);
            $QR = imagecreatefromstring(file_get_contents($filename));
            if($is_wxlogo){
                $logo = handleWXLogo($logo);
            }
            $logo = imagecreatefromstring(file_get_contents($logo));
            $QR_width = imagesx($QR);
            $QR_height = imagesy($QR);
            $logo_width = imagesx($logo);
            $logo_height = imagesy($logo);
            $logo_qr_width = $QR_width / 5;
            $scale = $logo_width / $logo_qr_width;
            $logo_qr_height = $logo_height / $scale;
            $from_width = ($QR_width - $logo_qr_width) / 2;
            imagecopyresampled($QR, $logo, $from_width, $from_width, 0, 0, $logo_qr_width, $logo_qr_height, $logo_width, $logo_height);
            if ($filename === false) {
                Header("Content-type: image/png");
                imagepng($QR);
            } else {
                if ($saveandprint === true) {
                    imagepng($QR, $filename);
                    header("Content-type: image/png");//输出到浏览器
                    imagepng($QR);
                } else {
                    imagepng($QR, $filename);
                }
            }
        }
        return $filename;
    }

    //微信图片处理
    function handleWXLogo($wxlogo){
        $url = $wxlogo;

        $header = array(
            'User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:45.0) Gecko/20100101 Firefox/45.0',
            'Accept-Language: zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3',
            'Accept-Encoding: gzip, deflate',
        );

        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($curl, CURLOPT_ENCODING, 'gzip');
        curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
        $data = curl_exec($curl);
        $code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
        curl_close($curl);
        if ($code == 200) {
            $imgBase64Code = "data:image/jpeg;base64," . base64_encode($data);
        }
        return $imgBase64Code;
    }

    /**
     * curl请求
     * 
     * @param string $data     请求的数据
     * @param string $url      请求地址
     * @param string $method   请求方式
     * @param string $dataType 请求数据格式
     */
    function curl($url,$data,$method='get',$dataType='json'){

        //初始化curl句柄，
        $ch = curl_init();
        /*设置不使用CA证书*/
        $opt[CURLOPT_SSL_VERIFYHOST] = 1;
        $opt[CURLOPT_SSL_VERIFYPEER] = FALSE;
        curl_setopt_array($ch, $opt);
        //设置服务器返回的数据不直接输出，而是保留在curl_exec()的返回值中
        curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
        if($method == 'get'){
            $data = urldecode(urlencode(http_build_query($data)));
            curl_setopt($ch,CURLOPT_URL,$url.'?'.$data);
        }else if($method == 'post'){
            curl_setopt($ch,CURLOPT_URL,$url);
            curl_setopt($ch,CURLOPT_POST,true);
            switch($dataType){
                case 'json':
                    $data = json_encode($data,JSON_UNESCAPED_UNICODE);
                break;
                case 'xml':
                    $xml = '<xml>';
                    foreach($data as $key => $val){
                        $xml .= '<'.$key.'>'.$val.'</'.$key.'>';
                    }
                    $xml .= '</xml>';
                    $data = $xml;
                break;
                default :
                    //$data = urldecode(http_build_query($data));
                break;
            }
            curl_setopt($ch,CURLOPT_POSTFIELDS,$data);
            curl_setopt($ch, CURLOPT_HTTPHEADER, array(   //如果添加了头部说明,dump($GLOBALS['HTTP_RAW_POST_DATA']);可以接受到
                'Content-Type: application/json',                            //如果没有添加头部说明   dump( file_get_contents("php://input")); 可以接受到
                'Content-Length: ' . strlen($data)
            ));
        }
        $return = curl_exec($ch);
        //获取返回的网络状态码
        $httpCode = curl_getinfo($ch,CURLINFO_HTTP_CODE);
        curl_close($ch);
        return $return;
    }

    /*
     * 根据经纬度计算两地的距离
     * $lat1, $lon1: 第一个点的经纬度
     * $lat2, $lon2: 第二个点的经纬度
     * $radius: 可选，默认为地球的半径
     */
    function sphere_distance($lat1, $lon1, $lat2 = 0, $lon2 = 0, $radius=6378.135) {
        $rad = doubleval(M_PI/180.0);
        $lat1 = doubleval($lat1) * $rad;
        $lon1 = doubleval($lon1) * $rad;
        $lat2 = doubleval($lat2) * $rad;
        $lon2 = doubleval($lon2) * $rad;
        $theta = $lon2 - $lon1;
        $dist = acos(sin($lat1) * sin($lat2) + cos($lat1) * cos($lat2) * cos($theta));
        if($dist < 0) {
            $dist += M_PI;
        }
        // 单位为 千米
        return $dist = round($dist * $radius);
    }

    /**
     * 发送消息
     *
     * @param  string $content          消息主体
     * @param  string $uid              推送对象
     * @return $data
     */
    function SendMsg($content = '测试消息',$uid = '')
    {
        $info = [
            'type' => 'publish',
            'content' => $content,
            'to' => $uid
        ];
        $url = 'http://121.40.157.186:2121';
        $ch = curl_init ();
        curl_setopt ( $ch, CURLOPT_URL, $url );
        curl_setopt ( $ch, CURLOPT_POST, 1 );
        curl_setopt ( $ch, CURLOPT_HEADER, 0 );
        curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
        curl_setopt ( $ch, CURLOPT_POSTFIELDS, $info );
        curl_setopt ($ch, CURLOPT_HTTPHEADER, array("Expect:"));
        $return = curl_exec ( $ch );
        curl_close ( $ch );
    }

    /**
     * 加密
     *
     * @param  string $prefix          加密前缀
     * @param  string $content         加密实体
     */
    function encryptMd($content = '',$prefix = '')
    {
        return md5($prefix.$content);
    }

    /**
     * 快递信息查询-快递100
     * @param       array        $param  
     * @return      array
     */
    function selectPostage($param)
    {
        //参数设置
        $post_data = array();
        $post_data["customer"] = '96C2F585F2543B0F6B507874A367E4A4';
        $key= 'BNuZHYPY9677' ;
        //$post_data["param"] = '{"com":"*****","num":"*****"}';
        $post_data['param'] = json_encode($param);
        $url='http://poll.kuaidi100.com/poll/query.do';
        $post_data["sign"] = md5($post_data["param"].$key.$post_data["customer"]);
        $post_data["sign"] = strtoupper($post_data["sign"]);
        $o="";
        foreach ($post_data as $k=>$v)
        {
            $o.= "$k=".urlencode($v)."&";       //默认UTF-8编码格式
        }
        $post_data=substr($o,0,-1);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        //设置服务器返回的数据不直接输出，而是保留在curl_exec()的返回值中
        curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_URL,$url);
        //设置请求头
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(   
            'Accept:application/json;charset=utf-8',
            'Content-Type:application/x-www-form-urlencoded;charset=utf-8'
        ));
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        $result = curl_exec($ch);
        $error = curl_error($ch);
        if($error){
            debug($error);
        }
        curl_close($ch);
        $data = str_replace("\"",'"',$result);
        $data = json_decode($data,true);
        return $data;
    }

    /**
     * fsockopen函数实现异步请求
     * @param   $url    string  请求地址
     * @param   $data  mix      请求参数
     * @param   $method string  请求方式，默认get
     * @param   $port   int     请求端口，默认80
     */
    function syncRequest($url,$data = [],$method = 'get',$port = 80){
        $info=parse_url($url);
        $fp = fsockopen($info["host"],$port);

        // 判断是否有数据
        if($data)
        {
            $query = urldecode(http_build_query($data)); // 数组转url 字符串形式
        }else
        {
            $query=null;
        }
        // 如果用户的$url "http://www.manongjc.com/";  缺少 最后的反斜杠
        if(!isset($info['path']) || empty($info['path']))
        {
           $info['path']="/index.php";
        }
        stream_set_blocking($fp,0); //stream_set_block()为资源流设置阻塞或者阻塞模式 0为非阻塞模式 1为阻塞模式
        // 判断 请求方式
        if($method=='post')
        {
            $head = "POST ".$info['path']." HTTP/1.0".PHP_EOL;
        }else
        {
            $head = "GET ".$info['path']."?".$query." HTTP/1.0".PHP_EOL;
        }

       $head .= "Host: ".$info['host'].PHP_EOL; // 请求主机地址
       //$head .= "Referer: http://".$info['host'].$info['path'].PHP_EOL;
        if($data && ($method=='post'))
        {
            $head .= "Accept:application/json;charset=utf-8";
            $head .= "Content-type: application/x-www-form-urlencoded".PHP_EOL;
            $head .= "Content-Length: ".strlen(trim($query)).PHP_EOL;
            $head .= PHP_EOL;
            $head .= trim($query);
        }else
        {
            $head .= PHP_EOL;
        }
        $write = fputs($fp, $head); //写入文件(可安全用于二进制文件)。 fputs() 函数是 fwrite() 函数的别名
        //debug($write);
        fclose($fp);
        return true;
        //feof() 函数用于判断是否达到文件末尾
        /*while (!feof($fp))
        {
            $line = fread($fp,4096);
            echo $line;
        }*/
    }

?>
